package sg.edu.nus.comp.cs4218.impl.fileutils;

import java.io.File;

import sg.edu.nus.comp.cs4218.fileutils.IEchoTool;
import sg.edu.nus.comp.cs4218.impl.ATool;
import sg.edu.nus.comp.cs4218.impl.Shell;

public class EchoTool extends ATool implements IEchoTool {

	/**
	 * Constructor
	 * 
	 * @param arguments
	 *            - Arguments the tool is going to be executed with.
	 */
	public EchoTool(String[] arguments) {
		super(arguments);
		setStatusCode(0);
	}

	/**
	 * Prints the provided string to screen
	 * 
	 * @param toEcho
	 *           - The string to print
	 * @return The string to print
	 */
	@Override
	public String echo(String toEcho) {
		return toEcho;
	}

	/**
	 * Prints the provided string to screen
	 * 
	 * @param stdin
	 *           - Input on stdin. NOT THE ARGUMENTS! Can be null.
	 * @return Output on stdout
	 */
	@Override
	public String execute(File workingDir, String stdin) {
		String toEcho = null;

		if (super.args == null && stdin != null) {
			super.args = Shell.parseIn(stdin);
		} else if (super.args == null && stdin == null) {
			setStatusCode(1);
			return "Invalid echo command";
		}

		for (String piece : super.args) {
			if (toEcho == null) {
				toEcho = piece;
			} else {
				toEcho = toEcho + " " + piece ;
			}

		}
		
		if (args.length == 0) {			
			toEcho = stdin;
		}
		
		if (toEcho == null) {
			toEcho = "";
		}
		return echo(toEcho);
	}
}
